<template>
  <j-modal :title="title" :width="width" :visible="visible" switchFullscreen @cancel="handleCancel" :footer="null">
    <div class="contentBox">
      <div class="formBox">
        <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="被检测人" v-if="isDisabled" required prop="realName">
            <a-input v-model="form.realName" :disabled="isDisabled" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="被检测人" required prop="sjskPersonId" v-else>
            <a-select style="width:100%;" v-model="form.sjskPersonId" allowClear>
              <a-select-option v-for="(item, index) in personList" :key="index" :value="item.id"
                @click.native="nameChange(item)">{{ item.realName }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="身份证号" required prop="identityCard">
            <a-input v-model="form.identityCard" :disabled="isDisabled || isDisabled1" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="检测类型" required prop="urineType">
            <a-select v-if="isUroscopy" v-model="form.urineType" :disabled="isDisabled || isDisabled1">
              <a-select-option value="1">常规尿液检测</a-select-option>
              <a-select-option value="2">突击尿液检测</a-select-option>
            </a-select>
            <a-select v-else v-model="form.urineType" :disabled="isDisabled || isDisabled1">
              <a-select-option value="3">常规毛发检测</a-select-option>
              <a-select-option value="4">突击毛发检测</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="检测次数" placeholder="请输入" required prop="detectNum">
            <a-input v-model="form.detectNum" :disabled="isDisabled || isDisabled1" />
          </a-form-model-item>
          <a-form-model-item label="开始时间" required prop="urineAppointmentStartTime">
            <a-date-picker v-model="form.urineAppointmentStartTime" style="width:100%;" show-time
              valueFormat="YYYY-MM-DD HH:mm:ss" placeholder="请选择" />
          </a-form-model-item>
          <a-form-model-item label="结束时间" required prop="urineAppointmentEndTime">
            <a-date-picker v-model="form.urineAppointmentEndTime" style="width:100%;" show-time
              valueFormat="YYYY-MM-DD HH:mm:ss" placeholder="请选择" />
          </a-form-model-item>
          <a-form-model-item label="检测对接信息">
            <div style="margin-top:8px;">
              <a-carousel arrows v-if="adressList.length > 0">
                <div slot="prevArrow" class="custom-slick-arrow" style="left: -4px;zIndex: 1">
                  <a-icon type="left" />
                </div>
                <div slot="nextArrow" class="custom-slick-arrow" style="right: -4px">
                  <a-icon type="right" />
                </div>
                <div class="itemBox" :class="[active == item.id ? 'itemBoxSelect' : '']" v-for="item in adressList"
                  :key="item.id" @click="onClick(item.id)">
                  <p>检测地点：<span>
                      <j-ellipsis :value="item.provinceCityAreaName" :length="12" />
                    </span></p>
                  <p>详细地址：<span>{{ item.detectCityAreaAddress }}</span></p>
                  <p>对 接 人：<span>{{ item.dockingName }}</span></p>
                  <p>联系电话：<span>{{ item.dockingPhone }}</span></p>
                </div>
              </a-carousel>
              <a-button class="btn" @click="onAdd" type="dashed" block>+ 添加检测对接信息</a-button>
            </div>
          </a-form-model-item>
        </a-form-model>
        <div class="btnBox">
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" :loading="loading" style="margin-left: 50px;" @click="onSubmit">确定</a-button>
        </div>
      </div>
      <AddCheckModal ref="addCheckModalId" title="添加检测对接信息" @ok=getAdress />
      <Schedule class="scheduleBox" ref="scheduleId" />
    </div>
  </j-modal>
</template>
<script>
import AddCheckModal from './AddCheckModal'
import Schedule from '@/views/sjsk/modules/Schedule'
import * as adressApi from '@/api/sjsk/check/adress.js'
import * as personServiceApi from '@/api/sjsk/personService.js'
import * as uroscopyApi from '@/api/sjsk/check/uroscopy.js'
import Vue from 'vue'
import { USER_INFO } from "@/store/mutation-types"
export default {
  name: 'BookingModal',
  props: ['title', 'isUroscopy'],
  components: {
    AddCheckModal,
    Schedule
  },
  data() {
    return {
      width: 1200,
      visible: false,
      labelCol: { span: 24 },
      wrapperCol: { span: 24 },
      form: {
        sjskPersonId: '',
        testNoticeId: '',
        realName: undefined,
        identityCard: undefined,
        urineType: undefined,
        detectNum: undefined,
        urineAppointmentStartTime: undefined,
        urineAppointmentEndTime: undefined
      },
      rules: {
        realName: [{ required: true, message: '请选择' }],
        sjskPersonId: [{ required: true, message: '请选择' }],
        identityCard: [{ required: true, message: '请输入' }],
        urineType: [{ required: true, message: '请选择' }],
        detectNum: [{ required: true, message: '请输入' }],
        urineAppointmentStartTime: [{ required: true, message: '请选择' }],
        urineAppointmentEndTime: [{ required: true, message: '请选择' }],
      },
      adressList: [],
      isDisabled: false,
      isDisabled1: false,
      active: "", //初始没有选中的项
      isAdd: true,
      loading: false,
      personList: [],
    }
  },
  async created() {
  },
  methods: {
    show(type, record) {
      console.log(type)
      this.visible = true
      this.form = {}
      this.active = ""
      this.isAdd = true
      if (type == 1) { //只能预约突击检测(非列表数据添加)
        this.isDisabled = false
        this.isDisabled1 = true
        if (this.isUroscopy) {
          this.form.urineType = '2' //只能预约突击尿检
        } else {
          this.form.urineType = '4' //只能预约突击发检
        }
        this.getSJSK() //获取社戒社康人员
      } else {//列表数据回填(列表数据添加)
        this.isDisabled = true
        this.form.id = record.id
        this.form.sjskPersonId = record.sjskPersonId
        this.form.realName = record.realName
        this.form.identityCard = record.identityCard
        this.form.urineType = record.urineType.toString()
        // this.form.detectNum = record.detectNum
        this.$set(this.form, "detectNum", "第" + record.detectNum + "次")
        if (type == 3) { //改约
          this.$set(this.form, 'urineAppointmentStartTime', record.urineAppointmentStartTime)
          this.$set(this.form, 'urineAppointmentEndTime', record.urineAppointmentEndTime)
          this.form.testNoticeId = record.testNoticeId
          this.active = record.testNoticeId //提交的项高亮显示
        }
      }
      this.getAdress() //获取地址信息列表
      this.getPlan() //获取日程预约数据
    },
    getSJSK() {
      let pageFilter = {
        pageNo: 1,
        pageSize: 1000,
      }
      personServiceApi.getPersonList(pageFilter).then(res => {
        if (res.success) {
          this.personList = res.result.records
        }
      })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    getMaxUrine(personId) {
      let params = {
        sjskPersonId: personId,
        urineType: 2, //1-定期；2-突击；3-毛发定期；4-毛发突击）
      }
      uroscopyApi.getMaxUrine(params).then(res => {
        if (res.success) {
          // this.form.detectNum = res.result
          // this.$set(this.form, 'detectNum', res.result)
          this.$set(this.form, "detectNum", "第" + res.result + "次")
        }
      })
    },
    nameChange(e) {
      console.log(e)
      // this.form.sjskPersonId = e.id
      this.form.realName = e.realName
      this.form.identityCard = e.identityCard
      this.getMaxUrine(e.id)
    },
    getAdress() {
      let pageFilter = {
        pageNo: 1,
        pageSize: 10,
      }
      adressApi.list(pageFilter).then((res) => {
        if (res.success) {
          this.adressList = res.result.records ? res.result.records : []
        }
      })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    getPlan() {
      let userInfo = Vue.ls.get(USER_INFO)
      uroscopyApi.planList(userInfo.id).then((res) => {
        if (res.success) {
          let scheduleData = []
          if (res.result.length > 0) {
            res.result.forEach(item => {
              if (item.overdue == 1) { //1为逾期，变红
                scheduleData.push({
                  id: item.id,
                  title: item.title,
                  start: item.startTime,
                  end: item.endTime,
                  overdue: item.overdue,
                  textColor: 'red',
                  className: ["bgColor", "monthRedColor"]
                })
              } else {
                scheduleData.push({
                  id: item.id,
                  title: item.title,
                  start: item.startTime,
                  end: item.endTime,
                  overdue: item.overdue,
                  textColor: '#000',
                  className: ["bgColor", "monthBlackColor"]
                })
              }
            })
            // console.log(list)
            // this.list.aa()
            // setTimeout(() => {
            //   console.log("scheduleData")
            //   console.log(scheduleData)
            // this.$refs.scheduleId.setScheduleData(scheduleData)
            this.$refs.scheduleId.setScheduleData(scheduleData, 'timeGridDay')
            // }, 1000)

          }
        }
        // this.scheduleData = [
        //   {
        //     id: 111,
        //     title: '张三的常规尿液检测11',
        //     start: '2022-12-3 02:30:00',
        //     end: '2022-12-10 06:00:00',
        //     overdue: "1"
        //   },
        //   {
        //     id: 222,
        //     title: '张三的常规尿液检测22',
        //     start: '2022-12-10 08:30:00',
        //     end: '2022-12-10 10:00:00',
        //     overdue: "1"
        //   },
        //   {
        //     id: 333,
        //     title: '吃药了吗',
        //     start: '2022-12-14 02:30:00',
        //     end: '2022-12-14 06:00:00',
        //     overdue: "2"
        //   },
        //   {
        //     id: 444,
        //     title: '林国强的常规尿液检测',
        //     start: '2022-12-16 02:30:00',
        //     end: '2022-12-16 06:00:00',
        //     overdue: "2"
        //   }]
        // this.$refs.scheduleId.setScheduleData(this.scheduleData)

      })
    },
    onClick(id) {
      this.active = id
      // console.log(this.form.testNoticeId, id)
      this.form.testNoticeId = id
    },
    onAdd() {
      this.$refs.addCheckModalId.show()
    },
    isSameDay(startTime, endTime) {
      const startTimeMs = new Date(startTime).setHours(0, 0, 0, 0);
      const endTimeMs = new Date(endTime).setHours(0, 0, 0, 0);
      return startTimeMs === endTimeMs ? true : false
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.testNoticeId == "" || this.form.testNoticeId == undefined) {
            this.$message.warning("请选择检测对接信息！")
            return
          }
          let flag = this.isSameDay(this.form.urineAppointmentStartTime, this.form.urineAppointmentEndTime)
          if (!flag) {
            this.$message.warning("预约开始时间和结束时间必须是同一天内！")
            return
          }
          this.form.detectNum = this.form.detectNum.substring(1, this.form.detectNum.length - 1) //截取数字字符,即次数
          //验证是否预约时间冲突
          let userId = Vue.ls.get(USER_INFO).id
          let params = {
            userId: userId,
            startTime: this.form.urineAppointmentStartTime,
            endTime: this.form.urineAppointmentEndTime
          }
          uroscopyApi.checkPlan(params).then(res => {
            if (res.success) {
              if (res.result) { //true表示预约时间冲突
                let that = this
                this.$confirm({
                  title: `当前时间段已有1个行程，确定要继续添加吗？?`,
                  okText: "确认",
                  okType: "danger",
                  cancelText: "取消",
                  onOk() {
                    that.addUrine()
                  }
                });
              } else { //无预约时间冲突
                this.addUrine()
              }
            }
          })
        }
      })
    },
    addUrine() {
      this.loading = true
      uroscopyApi.addUrineAppointment(this.form).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok');
          this.visible = false
          this.loading = false
        } else {
          this.loading = false
          this.$message.warn(res.message)
        }
      })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    handleCancel() {
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>
<style lang="less" scoped>
.contentBox {
  display: flex;
  height: 750px;
  position: relative;

  .formBox {

    flex: 1.2;
    height: 90%;
    overflow-y: auto;
    padding-right: 20px;

    .btnBox {
      position: absolute;
      bottom: 0;
      padding: 15px 0 0 70px;
      left: -20px;
      width: 320px;
      height: 60px;
      background-color: #fff;
    }
  }

  .scheduleBox {
    flex: 3;
    margin-left: 20px;
    padding-right: 20px;
  }
}

.itemBox {
  cursor: pointer;
  width: 90% !important;

  p {
    color: #000;
    text-align: left;
    font-size: 13px;
  }

  border: 1px solid #ccc;
  background-color:#fff;
  border-radius: 5px;
  padding: 10px 20px;
}

.itemBoxSelect {
  border: 1px solid #1890FF;
  background-color: #F4FAFF;
}

/deep/.ant-carousel {
  .slick-slide {
    text-align: center;
    height: 160px;
    overflow: hidden;
  }

  .custom-slick-arrow {
    width: 17px;
    height: 17px;
    font-size: 15px;
    color: #666;

    &:before {
      display: none;
    }

    &:hover {
      opacity: 0.5;
    }
  }
}

/deep/.ant-col-24 {
  text-align: left;
}

/deep/.ant-row {
  margin-bottom: 10px;
}


/deep/.ant-col-24 {
  padding-bottom: 5px;
}
</style>
